<script setup>
import { ref, onMounted } from 'vue'
// vant官方省市区数据
import { areaList } from '@vant/area-data'
import { useRoute, useRouter } from 'vue-router'
import { useAddressStore, useUserStore } from '@/stores/index.js'
import {
  useGetAreaListService,
  useGetAddressDetailService,
  useAddAddressService,
  useUpdateAddressService,
  useDelAddressService
} from '@/api/requsets/index.js'
import { showConfirmDialog, showToast } from 'vant'

const router = useRouter()
const route = useRoute()

// 用户信息仓库
// const userStore = useUserStore()

// 用户地址仓库
const addressStore = useAddressStore()

// 后台的省市区数据
const myAreaList = ref([])

const defId = ref()

onMounted(async () => {
  // todo 获取后台的省市区数据  注意：后台格式与官方格式不一致
  // todo 展示时以官方的数据驱动视图展示
  //  todo 修改 | 增加时 将官方的数据处理成  我们后台需要的数据格式 ！！！
  if (!addressStore.areaData) await addressStore.getAreaData()

  myAreaList.value = addressStore.areaData

  // 默认地址
  defId.value = addressStore.defAddressId

  // 判断是新增还是更改地址
  const mode = route.params.mode
  if (mode === 'update') {
    const { data: detail } = await useGetAddressDetailService(
      route.query.addressId
    )
    addressDetail.value = detail
  }
})
// 表单model对象
const addressDetail = ref(null)

// 点击保存后 修改地址 || 新增地址的回调
const onSave = async (item) => {
  // todo 将官方的数据格式转换为 后台数据格式

  const region = []
  // 官方 北京市 上海市  我方 北京 上海
  item.province = item.province.replace('市', '')

  for (let provinceKey in myAreaList.value) {
    if (myAreaList.value[provinceKey].name === item.province) {
      // 后台格式省份数据
      region.push({
        value: myAreaList.value[provinceKey].id,
        label: myAreaList.value[provinceKey].name
      })
    }
    // 后台格式城市数据
    for (let cityKey in myAreaList.value[provinceKey].city) {
      if (
        myAreaList.value[provinceKey].name === item.province &&
        myAreaList.value[provinceKey].city[cityKey].name === item.city
      ) {
        region.push({
          value: myAreaList.value[provinceKey].city[cityKey].id,
          label: myAreaList.value[provinceKey].city[cityKey].name
        })
      }

      // 后台格式 市区数据
      for (let regionKey in myAreaList.value[provinceKey].city[cityKey]
        .region) {
        if (
          myAreaList.value[provinceKey].name === item.province &&
          myAreaList.value[provinceKey].city[cityKey].name === item.city &&
          myAreaList.value[provinceKey].city[cityKey].region[regionKey].name ===
            item.county
        ) {
          region.push({
            value:
              myAreaList.value[provinceKey].city[cityKey].region[regionKey].id,
            label:
              myAreaList.value[provinceKey].city[cityKey].region[regionKey].name
          })
        }
      }
    }
  }
  const form = {
    name: item.name,
    phone: item.tel,
    region,
    detail: item.addressDetail
  }

  const mode = route.params.mode

  if (mode === 'update') {
    // todo 发送修改请求
    await useUpdateAddressService({ addressId: route.query.addressId, form })
    await addressStore.getUserAddressData()
    await router.push('/address')
    showToast('修改成功')
  } else {
    // todo 发送增加请求
    await useAddAddressService({ form })
    await addressStore.getUserAddressData()
    showToast('增加成功')
    await router.push('/address')
  }
}

// 点击删除的回调
const onDel = async () => {
  showConfirmDialog({
    title: '温馨提示',
    message: '您确定要删除该地址吗？'
  }).then(async () => {
    await useDelAddressService({ addressId: route.query.addressId })
    await addressStore.getUserAddressData()
    showToast('删除成功')
    await router.push('/address')
  })
}
</script>

<template>
  <van-nav-bar
    :title="$route.query.mode === 'add' ? '新增地址' : '修改地址'"
    left-arrow
    @click-left="$router.go(-1)"
  />
  <van-address-edit
    show-delete
    :area-list="areaList"
    :address-info="{
      name: addressDetail?.detail?.name,
      tel: addressDetail?.detail?.phone,
      province: addressDetail?.detail?.region.province,
      city: addressDetail?.detail?.region.city,
      county: addressDetail?.detail?.region.region,
      addressDetail: addressDetail?.detail?.detail
    }"
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    :detail-rows="2"
    :detail-maxlength="80"
    :tel-validator="
      (phone) => {
        return /^1(3[0-9]|4[579]|5[0-35-9]|6[567]|7[0135678]|8[0-9]|9[0-8])\d{8}$/.test(
          phone
        )
      }
    "
    @save="onSave"
    @delete="onDel"
  />
</template>

<style scoped lang="less"></style>
